<template>
	<view>
		<button @click="getCode()" data-eventsync="true">获取信息</button>
		<button @click="chooseavatar"> 头像</button>
		<button @click="gouser"> 昵称</button>


		<button @click="getCodet()">11</button>
		<button  @click="getCodett()">22登录成功，token存储成功</button>
	</view>

</template>

<script>
	import {
		data
	} from 'uview-ui/libs/mixin/mixin';

	import uView from 'uview-ui';
	
	import { wxLogin, wxlogin } from '@/config/api.js'
	import { mapActions } from 'vuex';
	export default {
		
	

		data() {
			return {
				isLogin: 1,
				code: "",
				isLogin: false,
				avatar: "",
				nickName: "",



				userLoginDTO: {
					"nickname": "user123",
					"gender": "0",
					"avatarurl": "dfee",
					"code": "0b3ME3000TBOcR1zbm100iTKSC3ME30O"
				}
			};
		},
		methods: {
			//...mapActions(['wxlogin']), 
			// 如果使用 Vuex 进行状态管理，需要将 login 方法映射到组件中
			
			 getCodett(){
				let _this = this;
				wx.login({
					success:async (res)=>{
						if (res.code) {
							_this.code = res.code;
							const params = {
								code:res.code
							}
							try{
								  const data = await  wxlogin(params);
								  
								  console.log("成功res.data"+JSON.stringify(data))
								  this.$store.commit('setUserInfo',data); // 将数据保存到store中
								   console.log("store-wxtoken"+JSON.stringify(this.$store.state.userInfo)); // 打印userInfo
								  
						
							}catch(error){
								console.log("try WxLogin报错登录后台失败");
							}
							
						
				
							
						} else {
							console.log("请求code失败或code为空");
						}
					},fail:(error)=>{
						console.log("wx.login调用失败", error);
					}
				}
				
				
				);
							
			},
			//getCodett--end
			
			
			
			getCodet() {
				let _this = this;
				wx.login({
					success:(res)=>{
						if (res.code) {
							_this.code = res.code;
							try{
								  const data =    _this.handleLogin(res.code);
								console.log("成功res.data"+JSON.stringify(data))
							}catch(error){
								console.log("login报错登录后台失败");
							}
							
						

							
						} else {
							console.log("请求code失败或code为空");
						}
					},fail:(error)=>{
						console.log("wx.login调用失败", error);
					}
				}
				
				
				);
			
			
			},
			
			
			
			 async handleLogin(code) {
				console.log(code)
			    try {
			      const params = {
			        
			        code: code
			      }
			      const res = await wxlogin(params,{
					  auth:false
				  })
				  //,{
				  //auth: false // 不需要token
				  //}
				  
				  
				  console.log('success.data:'+JSON.stringify(res.data));
				  this.$store.commit('setUserInfo',res.data); // 将数据保存到store中
					console.log('111request success:res.data:', res.data);
					return res;
				} catch (error) {
			      // 处理登录失败后的逻辑
				  console.log('request fail', error)
				  return Promise.reject(error)
			    }
			  },
			
			
			
			
			
			async jumptologin(code) {

				//await this.getCode();

				await uni.request({
					url: 'http://localhost:8080/user/wxlogin',
					method: 'PUT',
					data: {
						//http://qqyu5e.natappfree.cc
						//http://8.134.69.204:8080/user/wxlogin
						//http://localhost:8080/user/wxlogin
						//nickname: 'user123',
						//gender: 0,
						//avatarurl: 'dfee',
						code: code
					},
					success: function(res) {
						console.log('request success res', res)
						console.log('request success res.data.data', res.data)
						console.log('request success res.data.data.wxtoken', res.data.data.wxtoken)
						uni.setStorageSync('userInfo', res.data.data.wxtoken);
					},
					fail: function(err) {
						console.log('request fail', err)
					}
				})
			},




			loginqqq() {
				let data = {
					...this.form
				}
				this.$api({
					method: 'put',
					url: 'user/wxlogin',
					data: data
				}).then(res => {
					if (res.code == 200) {
						// 存入本次缓存中
						uni.setStorageSync('userInfo', res.data);
						this.$u.toast('登录成功');
						uni.navigateBack();
					} else {
						this.$u.toast(res.msg);
					}
				}).catch(err => {
					console.log(err)
				});
			},
			//loginqqq--end




			// 登录方法
			async login(code) {
				let that = this
				//调用自己封装的方法
				var res = await api.LoginByWeChat(code)
				//登录成功跳转页面
				if (res.successed) {
					this.$refs.uToast.show({
						type: 'success',
						message: res.message,
						complete() {
							that.$store.state.token = res.token
							//为了用动画所以用了navigateTo
							uni.navigateTo({
								url: '/pages/mine/mine'
							})
						}
					})
				} else {
					this.$refs.uToast.show({
						type: 'error',
						message: res.message
					})
				}
			},
			//login--end

			//getUserProfile--end




			//小程序登录
			/**
			 * 步骤一：获取code，通过uni.login或者wx.login
			 */
			getCode() {
				let _this = this;
				wx.login({
					success(res) {
						if (res.code) {
							_this.code = res.code;
							_this.jumptologin(res.code)
							console.log(res.code)
							//_this.getUser()
						} else {
							console.log("登录失败");
						}
					},
				});


			},

			/**
			 * 步骤二：code换取sessionKey，openid等信息，去登录，获取token
			 */


			//获取用户头像，获取到的头像是临时文件，要通过自己的上传接口上传到服务器
			chooseavatar(e) {
				console.log(e);
				this.avater = e.detail.avatarUrl;
				this.$uploadFile(this.avater)
					.then((image) => {
						console.log(image);
						this.avater = image.data.fullurl;
					});
				this.isLogin = 3;
			},
			//chooseavatar--end

			//步骤四：获取微信昵称
			gouser() {
				let that = this;
				uni.createSelectorQuery().in(this).select("#nickname-input").fields({
					properties: ["value"],
				}).exec((res) => {
					that.nickname = res?.[0]?.value;
					setTimeout(() => {
						if (typeof that.nickname === 'string' && that.nickname.trim().length === 0) {
							uni.showToast({
								title: "请输入昵称！",
								icon: "none",
							});
							return;
						}
						let params = {
							nickname: that.nickname,
							avatar: that.avater,
						};
						console.log(params);
						that.$postAction("user/profile", params).then((res) => {
							uni.switchTab({
								url: "/pages/tabBarView/home",
							});
						});
					}, 100);
				});
			},
			//gouser--end

			//methods --end
		},
	};
</script>

<style>

</style>